import api from "../../../../config/api"
import request from "../../../../utils/request"
import { getStorage } from "../../../../utils/utils"

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    display: {
      type: Boolean,
      value: '',
      observer(newVal) {
        this.setData({
          displayTag: newVal,
        })
      },
    },
    conversation: {
      type: Object,
      value: {},
      observer(newVal) {
        this.setData({
          conversation: newVal,
        })
      },
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabIndex: '1',
    displayTag: true,
    words: '',
    orderMatch: [],
  },

  lifetimes: {
    ready() {
      this.getList()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    handleClose() {
      this.triggerEvent('close', {
        key: '1',
      })
    },
    wordsInput(e) {
      this.data.orderMatch = [],
      orderList.forEach((item) => {
        if (item.title.indexOf(e.detail.value) > -1 || item.orderNum === ~~e.detail.value) {
          this.data.orderMatch.push(item)
        }
      })
      this.setData({
        words: e.detail.value,
        orderMatch: this.data.orderMatch,
      })
    },
    sendMessage(e) {
      const { order } = e.currentTarget.dataset
      this.triggerEvent('sendCustomMessage', {
        payload: {
          // data 字段作为表示，可以自定义
          data: 'order',
          extension: JSON.stringify({
            id: order.goodsId,
            title: order.goodsTitle || '商品暂无描述信息',
            imageUrl: order.url,
            price: order.goodsPrice
          }),
        },
      })
    },
    // 标签页选中变化
    tabChange(e) {
      const tabIndex = e?.currentTarget?.dataset?.index
      if (tabIndex === this.data.tabIndex) return
      this.setData({
        tabIndex,
      })
      this.getList()
    },
    /**
     * 获取列表
     */
    async getList() {
      const { tabIndex, conversation } = this.data
      if (tabIndex === '1' && !conversation?.conversationID) {
        setTimeout(() => {
          this.getList()
        }, 200)
        return
      }
      const userId = tabIndex === '1'
        ? conversation?.conversationID?.split?.('_')?.pop()
        : getStorage('userId')
      const res = await request.get(api.imGoodsList, { userId })

      this.setData({
        orderMatch: res?.data || [],
      })
    },
  },
})
